using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace EditDeploymentSettings
{
	public class DeploymentEnvironment
	{
		private string _fileName;
		private SortedDictionary<string, string> _properties = new SortedDictionary<string, string>();

		public DeploymentEnvironment(string fileName)
		{
			_fileName = fileName;
			Load();
		}

		public string FileName
		{
			get { return _fileName; }
		}

		public string EnvironmentName
		{
			get { return Path.GetFileName(_fileName); }
		}

		public SortedDictionary<string,string> Properties
		{
			get { return _properties; }
			set { _properties = value; }
		}

		public bool Load()
		{
			_properties.Clear();
			return Load(_fileName);
		}

		public bool Load(string fileName)
		{
			XmlDocument doc = new XmlDocument();
			doc.Load(fileName);

			XmlNodeList settings = doc.SelectNodes("//property");

			foreach (XmlElement setting in settings)
			{
				_properties.Add(setting.GetAttribute("name"), setting.InnerText);
			}

			return true;
		}

		public bool Save()
		{
			return Save(_fileName);
		}

		public bool Save(string fileName)
		{
			XmlDocument doc = new XmlDocument();
			XmlElement rootElement = doc.CreateElement("settings");
			doc.AppendChild(rootElement);
			foreach (string key in _properties.Keys)
			{
				XmlElement settingElement = doc.CreateElement("property");
				settingElement.SetAttribute("name", key);
				settingElement.InnerText = _properties[key];

				string val = _properties[key];
				if (!string.IsNullOrEmpty(val))
				{
					settingElement.InnerText = val;
				}
				else
				{
					settingElement.IsEmpty = true;
				}

				rootElement.AppendChild(settingElement);
			}

			FileInfo fi = new FileInfo(fileName);
			fi.IsReadOnly = false;
			doc.Save(fileName);

			return true;
		}
	}
}
